import Model from '../abstract';

export default class ModelUserGroup extends Model {
      
      constructor() {
            super();
            this.mainTable = 'user_group';
            this.pk = 'group_id';
            this.serverPk = 'server_group_id';
            this.versionName = 'version';
            this.dateAddedName = 'date_added';
            this.lastUpdatedName = 'last_updated';
      }

      /**
       * 获取单个group的权限
       */
      async getPermission(groupId) {
            let row = await this.fetchOne("SELECT `permission` FROM `user_group` WHERE `group_id` = ? LIMIT 0,1", [groupId]);
            if (row && row.permission) {
                  return JSON.parse(row.permission);
            }
            return null;
      }

      /**
       * 数据删除
       */
      async removeGroup(groupId) {
            await this.delete("user_to_group", {group_id: groupId});
            await this.remove(groupId);
      }

      /**
       * 根据serverPK删除数据
       */
      async removeGroupByServerPk(serverPk) {
            let groupId = await this.getIdByServerPk(serverPk);
            if (groupId > 0) {
                  return await this.removeGroup(groupId);
            }
            return false;
      }

      /**
       * 数据导入
       */
      async download(rows = []) {
            if (!Array.isArray(rows)) {
                  rows = [];
            }

            let localServerPks = await this.getServerPks();
            let remoteServerPks = [];
            for (row of rows) {
                  let serverPk = row.server_group_id;
                  remoteServerPks.push(serverPk);
                  let pk = await this.saveByServerPk(row, serverPk);
                  console.log("group >>>> ", pk);
            }

            let delServerPks = localServerPks.filter(el => !remoteServerPks.includes(el));
            for (serverPk of delServerPks) {
                  if (serverPk > 0) {
                        await this.removeGroupByServerPk(serverPk);
                  }
            }
            
            return true;
      }

      /**
       * 数据上传
       */
      async upload() {
            return true;
      }

}